package utils;

import java.io.FileInputStream;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

public class JDBCUtil {
	private static String username;
	private static String password;
	private static String url;
	private static String driverClassName;
	
	static {
		try {
			Properties properties = new Properties();
			properties.load(JdbcUtils.class.getClassLoader().getResourceAsStream("jdbc.properties"));
			driverClassName =properties.getProperty("driverClassName");
			username = properties.getProperty("username");
			password = properties.getProperty("password");
			url = properties.getProperty("url");
		} catch(IOException e) {
			throw new RuntimeException(e);
		}
	}
	//连接数据库返回Connection
	public static Connection getConnection() {
		try {
			//1. 加载驱动
	        try {
				Class.forName(driverClassName);
			} catch (ClassNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
	        //2. 获取连接
			return DriverManager.getConnection(url,username,password);
		} catch(SQLException e) {
			throw new RuntimeException(e);
		}
	}
	//6关闭资源
	public static void close(ResultSet set, Statement statement, Connection connection) {
		try {
			if (set != null) {
				set.close();
			}
			if (statement != null) {
				statement.close();
			}
			if (connection != null) {
				connection.close();
			}
		} catch (SQLException e) {
			// 将编译异常转成运行异常抛出
			throw new RuntimeException(e);
		}
	}
}
